#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <X11/extensions/XTest.h>
#include <X11/keysym.h>
#include <fcntl.h>

// RS232 barcode driver for X11
// Copyright (C) 2007 Alexis ROBERT

// Only work with numbers

int main(int argc, char **argv) {
	printf("RS232 barcode driver for X11\n");
	printf("Copyright (C) 2007 Alexis ROBERT (Under GPL2)\n\n");
	printf("WARNING : Numlock MUST be on !\n\n");

	printf("- Opening X11 display ...\n");
	Display* disp = XOpenDisplay(NULL);
	if (disp == NULL) return 1;

	printf("- Opening serial port ...\n");
	FILE *serialport = fopen("/dev/ttyS0", "r");

	while (!feof(serialport)) {
		char *content = malloc(1024*sizeof(char));
		fread(content,sizeof(char),1024,serialport);
		while (*content) {
			KeySym keysym = 0;
			switch (*content) {
				case '0': keysym = XK_KP_0; break;
				case '1': keysym = XK_KP_1; break;
				case '2': keysym = XK_KP_2; break;
				case '3': keysym = XK_KP_3; break;
				case '4': keysym = XK_KP_4; break;
				case '5': keysym = XK_KP_5; break;
				case '6': keysym = XK_KP_6; break;
				case '7': keysym = XK_KP_7; break;
				case '8': keysym = XK_KP_8; break;
				case '9': keysym = XK_KP_9; break;
				case '\n': keysym = XK_KP_Enter; break;
			}
			if (keysym != 0) {
				if (keysym == XK_KP_Enter)
					printf("- Barcode scanned !\n");
				XTestFakeKeyEvent(disp, XKeysymToKeycode(disp, keysym), False, CurrentTime);
			}
			content++;
		}
	}

	printf("- Freeing data ...\n");
	fclose(serialport);

	XCloseDisplay(disp);
	return 0;
}
